package com.ruoyi.scope.service.impl;


import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.scope.domain.Scope;
import com.ruoyi.scope.mapper.ScopeMapper;
import com.ruoyi.scope.service.ScopeService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

/**
 * 经营范围基础Service业务层处理
 *
 * @author zjh
 * @date 2022-04-08
 */
@Service
public class ScopeServiceImpl implements ScopeService {
    @Autowired
    private ScopeMapper scopeMapper;

    /**
     * 查询经营范围基础
     *
     * @param scopeId 经营范围基础ID
     * @return 经营范围基础
     */
    @Override
    public Scope selectScopeById(Long scopeId)
    {
        return scopeMapper.selectScopeById(scopeId);
    }

    /**
     * 查询经营范围基础列表
     *
     * @param scope 经营范围基础
     * @return 经营范围基础
     */
    @Override
    public List<Scope> selectScopeList(Scope scope)
    {
        return scopeMapper.selectScopeList(scope);
    }

    /**
     * 新增经营范围基础
     *
     * @param scope 经营范围基础
     * @return 结果
     */
    @Override
    public int insertScope(Scope scope)
    {
        String s;
        if(scope.getProductRemark().isEmpty()){
            s=scope.getProductClass()+scope.getProductDesc();
        }else {
            s=scope.getProductClass()+scope.getProductDesc()+'（'+scope.getProductRemark()+'）';
        }
        scope.setScopeInfo(s);
        return scopeMapper.insertScope(scope);
    }

    /**
     * 修改经营范围基础
     *
     * @param scope 经营范围基础
     * @return 结果
     */
    @Override
    public int updateScope(Scope scope)
    {
        scope.setUpdateTime(DateUtils.getNowDate());
        String s;
        if(scope.getProductRemark().isEmpty()){
            s=scope.getProductClass()+scope.getProductDesc();
        }else {
            s=s=scope.getProductClass()+scope.getProductDesc()+'（'+scope.getProductRemark()+'）';
        }
        scope.setScopeInfo(s);
        return scopeMapper.updateScope(scope);
    }

    /**
     * 删除经营范围基础对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteScopeByIds(String ids)
    {
        return scopeMapper.deleteScopeByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除经营范围基础信息
     *
     * @param scopeId 经营范围基础ID
     * @return 结果
     */
    @Override
    public int deleteScopeById(Long scopeId)
    {
        return scopeMapper.deleteScopeById(scopeId);
    }

    /**
     * 根据生产类别与管理类别查询数量
     *
     * @param scopeClass,productClass 查询条件
     * @return 结果
     */
    public Integer selectScopeByName(String scopeClass, String productClass){return scopeMapper.selectScopeByName(scopeClass,productClass);}

    /**
     * 根据生产类别与管理类别查询id
     *
     * @param scopeClass,productClass 查询条件
     * @return 结果
     */
    public Long selectScopeIdByName(String scopeClass, String productClass){return scopeMapper.selectScopeIdByName(scopeClass,productClass);}



    /**
     * 导入用户数据
     *
     * @param scopeList 用户数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public String importScope(MultipartFile file,List<Scope> scopeList, String operName) throws Exception {
        InputStream inputStream = file.getInputStream();
        String filename = file.getOriginalFilename();
        Workbook wb = null;
        // 根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
        Iterator<Sheet> sheets = null;
        if (filename.endsWith("xls")) {
            wb = new HSSFWorkbook(inputStream);
            sheets = wb.iterator();
        } else if (filename.endsWith("xlsx")) {
            wb = new XSSFWorkbook(inputStream);
            sheets = wb.iterator();
        }
        if (sheets == null) {
            throw new Exception("excel中不含有sheet工作表");
        }
        Sheet sheet = sheets.next();

        // 判断表头
        Row titleRow = sheet.getRow(0);
        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        list1.add("管理类别");
        list1.add("产品类别");
        list1.add("类别描述");
        list1.add("类别备注");
        for (int x = 0; x < 4; x++) {
//            list2.add(titleRow.getCell(x).getStringCellValue());
            Cell cell=titleRow.getCell(x);
//            cell.setCellType(CellType.STRING);
            list2.add(cell.getStringCellValue());
        }
        if (!list1.containsAll(list2)) {
            throw new RuntimeException("导入文件表头与模板不一致！");
        }
        if (StringUtils.isNull(scopeList) || scopeList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        int successNum = 0;
        int failureNum = 0;
        Scope scopes = null;
        List<Scope> exist=scopeMapper.selectScopeList(scopes);
        List<Scope> model=new ArrayList();

        List<String> list3 = new ArrayList<>();
        for (Scope scope : scopeList) {
            //将管理类别与产品类别进行拼接，不一样将内容加入list3，scope继续与数据库进行比较，若是list3中包含了则说明数据重复。
            if(list3.contains(scope.getScopeClass()+scope.getProductClass())){
                failureNum ++;
                continue;
            }
            list3.add(scope.getScopeClass()+scope.getProductClass());
            //将用户输入的数据转换成数据字典可以识别数据库中存储的数值
            if(scope.getScopeClass().contains("I类")){
                scope.setScopeClass("0");
            }else if(scope.getScopeClass().contains("Ⅱ类")){
                scope.setScopeClass("1");
            }else{
                scope.setScopeClass("2");
            }
            for(Scope scopeexist:exist){
                if (scopeexist.getScopeClass().equals(scope.getScopeClass())  && scopeexist.getProductClass().equals(scope.getProductClass())){
                    successNum=0;
                    failureNum ++;
                    break;
                }else {
                    successNum=1;
                }
            }
            if(successNum==1||exist.size()==0){
                try {
                    // 验证是否存在这个用户
                    String s;
                    if(scope.getProductRemark().isEmpty()){
                        s=scope.getProductClass()+scope.getProductDesc();
                    }else {
                        s=s=scope.getProductClass()+scope.getProductDesc()+'（'+scope.getProductRemark()+'）';
                    }
                    scope.setScopeInfo(s);
                    scope.setCreatBy(operName);
                } catch (Exception e) {
                    String msg = "<br/>"  + "、账号 " + SecurityUtils.getLoginUser().getUserName() + " 导入失败：";
                    failureMsg.append(msg + e.getMessage());
                }
                model.add(scope);
                successNum=0;
            }
        }
        if (model.size() > 0) {
            int num =scopeMapper.insertScopes(model);
            if (num > 0) {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + num + " 条,"+failureNum+"条数据重复！");
            }
        } else if(model.size() == 0) {
            failureMsg.insert(0, "导入失败，数据已全部存在！");
            throw new Exception("导入失败，数据已全部存在！");
        }else {
            failureMsg.insert(0, "导入失败！");
            throw new Exception("导入失败！");
        }
        return successMsg.toString();
    }



    /**
     * 下载模板
     */
    public String exportTemp() {
        HSSFWorkbook workbook = new HSSFWorkbook();// 创建Excel文件(Workbook)

        HSSFSheet sheet = null;// 创建工作表(Sheet)

        sheet = workbook.createSheet("sheet1");// 创建工作表(Sheet)

        HSSFRow row0 = sheet.createRow(0);

        List<String> haed1 = new LinkedList<>();
        haed1.add("管理类别");
        haed1.add("产品类别");
        haed1.add("类别描述");
        haed1.add("类别备注");

        Map<String, List> haed = new HashMap<>();
        haed.put("经营范围信息", haed1);

        int i = 0;
        for (Map.Entry<String, List> entry : haed.entrySet()) {

            HSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);//水平居中
            style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
            style.setBorderBottom(BorderStyle.THIN);
            style.setBottomBorderColor(IndexedColors.AUTOMATIC.getIndex());
            style.setBorderRight(BorderStyle.THIN);
            style.setRightBorderColor(IndexedColors.AUTOMATIC.getIndex());

            style.setBorderTop(BorderStyle.THIN);
            style.setTopBorderColor(IndexedColors.AUTOMATIC.getIndex());
            for (int j = 0; j < entry.getValue().size(); j++) {
                HSSFCell cell1 = row0.createCell(i);
                cell1.setCellStyle(style);
                cell1.setCellValue(entry.getValue().get(j).toString());
                i++;
            }

            String[] typelist = {"I类", "Ⅱ类", "Ⅲ类"};
            DVConstraint typeConstraint = DVConstraint
                    .createExplicitListConstraint(typelist);
            CellRangeAddressList regions = new CellRangeAddressList(0,
                    100, 0, 0);
            HSSFDataValidation data_validation_view = new HSSFDataValidation(
                    regions, typeConstraint);
            sheet.addValidationData(data_validation_view);

        }

        String localPath = RuoYiConfig.getProfile() + "/download/" + UUID.randomUUID().toString();

        // 生成文件夹
        File file = new File(localPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 填充数据
        try {
            FileOutputStream out = new FileOutputStream(localPath + "/" + "导入经营范围模板.xls");
            workbook.write(out); // 保存Excel文件
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return localPath + "/" + "导入经营范围模板.xls";

    }

    @Override
    public Long selectScopeIdByNameAndProductRemark(String scopeClass, String productClass, String productRemark) {
        return scopeMapper.selectScopeIdByNameAndProductRemark(scopeClass,productClass,productRemark);
    }
}
